package video.simple100;

import org.junit.Test;

/***
 * 226. 翻转二叉树
 */
public class LeetCode226 {


    @Test
    public void test() {
        TreeNode treeNode1 = new TreeNode(1);
        TreeNode treeNode2 = new TreeNode(2);
        TreeNode treeNode3 = new TreeNode(3);
        treeNode2.left = treeNode1;
        treeNode2.right = treeNode3;
        invertTree(treeNode2);
    }

    public TreeNode invertTree(TreeNode root) {
        // 解题思路
        // 1、进行树的遍历
        // 2、在遍历的过程中把左节点的值给右节点，把右节点的值给左节点
        nextTreeNode(root);
        return root;
    }


    // 遍历
    void nextTreeNode(TreeNode root) {
        if (root == null) {
            return;
        }
        // System.out.println(root.val);

        // 临时存一下左节点的值，(右也可以)
        TreeNode vLeft = root.left;
         // 把左节点的值替换成右节点的值
        root.left = root.right;
        // 在临时存左节点的值给右节点
        root.right = vLeft;

        // 递归遍历
        nextTreeNode(root.left);
        nextTreeNode(root.right);
    }


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
